package com.example.parallelandroid;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.parallelandroid.entity.Region;
import com.example.parallelandroid.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RankingFragment extends Fragment {

    //排行榜的listview
    private ListView dataListView;
    //地区的gridview
    private GridView cnRegion;
    //listview的适配器 gridview的适配器
    private DataListAdapter listAdapter;
    private RegionAdapter regionAdapter;
    //排行榜的list 地区的list
    private List<Data> dataList = new ArrayList<>();
    private List<Region> regionList=new ArrayList<>();
    //使用须知的按钮
    private Button btnUseKnowledge;
    //刷新布局控件
    private SmartRefreshLayout refreshLayout;
    //榜单下拉框
    private Spinner spinner;
    //下拉框的适配器
    private ArrayAdapter spinnerAdapter;
    //判断是刷新还是加载
    private boolean isRefresh = true;
    //Handler里用于刷新页面的常量
    private final int REFRESH = 1;
    //初始状态下当前页为1  一次拿6条数据
    private int page = 1;
    private int size = 6;
    //判断是否选择了地区的字符串 没有选择地区就是0
    //为1时说明用户设置了省份 并且选择了省内
    //为2时说明用户选择了全国 设不设置省份都可以 不设置省份就显示未知
    //为3说明用户选择了省内 但是没设置省份
    private String selectBelow="0";
    //用于存放每次请求数据的jsonArray
    private JSONArray jsonArray;
    //一直在变化的url 用于向后端请求数据
    private String url;
    //用于取出省份的工具
    private SharedPreferences sharedPreferences;
    //用户当前的省份
    private String province;
    //用于刷新页面的Handler
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            switch (msg.what){
                case REFRESH:
                    //刷新ListView
                    listAdapter.notifyDataSetChanged();
                    //结束刷新和加载的动画
                    if (isRefresh){
                        refreshLayout.finishRefresh();
                    }else {
                        refreshLayout.finishLoadMore();
                    }
                    break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 获取布局文件
        View view = inflater.inflate(R.layout.fragment_ranking, null);
        //获取下拉框控件
        spinner=view.findViewById(R.id.lv_spinner);
        //获取地区gridview控件
        cnRegion=view.findViewById(R.id.cn_region);
        //获取刷新布局控件
        refreshLayout = view.findViewById(R.id.lv_srl);
        //获取排行榜的listview控件
        dataListView = view.findViewById(R.id.lv_datas);
        //获取使用须知的按钮
        btnUseKnowledge=view.findViewById(R.id.btn_use_knowledge);
        initSettings();
        return view;
    }
    //初始化地区Gridview的数据
    private void initRegionData(){
        Region provinceRegion=new Region();
        provinceRegion.setRegion("省内");
        provinceRegion.setPicture(R.drawable.province);
        regionList.add(provinceRegion);
        Region chinaRegion=new Region();
        chinaRegion.setRegion("全国");
        chinaRegion.setPicture(R.drawable.china);
        regionList.add(chinaRegion);
    }
    //初始化各种适配器并绑定 设置点击事件 下拉刷新 上拉加载各种事件
    private void initSettings(){
        sharedPreferences= getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd");
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
        });
        Gson gson = builder.create();
        UserInfo userInfo=gson.fromJson(sharedPreferences.getString("userInfo",""),UserInfo.class);
        province=userInfo.getProvince();
        //初始化下拉框的适配器
        spinnerAdapter = ArrayAdapter.createFromResource(getContext(), R.array.plantes, android.R.layout.simple_spinner_item);
        //设置下拉列表的风格
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将spinnerAdapter 添加到spinner中
        spinner.setAdapter(spinnerAdapter);
        //初始化地区Gridview的数据
        initRegionData();
        //设置地区gridview的适配器并绑定
        regionAdapter=new RegionAdapter(getContext(), regionList,R.layout.region_item);
        cnRegion.setAdapter(regionAdapter);
        //使用须知按钮的点击事件
        btnUseKnowledge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1创建Builder对象
                AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
                //2设置属性参数
                // 设置标题 提示文本、确定及取消按钮
                builder.setTitle("使用须知")
                        .setMessage("1.当您选择地区后 数据才会出现\n" +
                                "2.昵称为红色的数据代表您的数据\n"+
                                "3.当您选择地区后 可以更换榜单\n"+
                                "4.点击任意一条数据 可以进入数据详情页")
                        .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                //3创建AlertDialog对象
                AlertDialog dialog=builder.create();
                //4显示对话框
                dialog.show();
            }
        });
        //处理下拉刷新和上拉加载更多事件的方法
        setListener();
        //设置排行榜list的适配器并绑定
        listAdapter = new DataListAdapter(getContext(), dataList, R.layout.data_list_item);
        dataListView.setAdapter(listAdapter);
        //设置地区gridview的点击事件
        cnRegion.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dataList.clear();
                page=1;
                selectBelow=position+1+"";
                Constant.spinnerContent=spinner.getSelectedItem().toString();
                switch(selectBelow){
                    //说明点击的是省份
                    case "1":
                        if(province==null){
                            selectBelow="3";
                            Toast.makeText(getContext(), "您还没有设置省份！", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        switch(Constant.spinnerContent){
                            case "综合榜":
                                url=Constant.BASE_URL + Constant.url11 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            case "智力榜":
                                url=Constant.BASE_URL + Constant.url21 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            case "体力榜":
                                url=Constant.BASE_URL + Constant.url31 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            case "魅力榜":
                                url=Constant.BASE_URL + Constant.url41 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                        }
                        break;
                    //说明点击的是全国
                    case "2":
                        switch(Constant.spinnerContent){
                            case "综合榜":
                                url=Constant.BASE_URL + Constant.url12 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "智力榜":
                                url=Constant.BASE_URL + Constant.url22 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "体力榜":
                                url=Constant.BASE_URL + Constant.url32 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "魅力榜":
                                url=Constant.BASE_URL + Constant.url42 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                        }
                        break;
                }
                if(selectBelow.equals("3")){
                    dataList.clear();
                    listAdapter.notifyDataSetChanged();
                    //是3的话说明是从没选择省份出来的 不做操作
                }else{//不是3 是1 2 都请求数据
                    getData();
                }
            }
        });
        //设置榜单下拉框的点击事件
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dataList.clear();
                page=1;
                Constant.spinnerContent=spinner.getSelectedItem().toString();
                switch(Constant.spinnerContent){
                    //1代表综合榜
                    case "综合榜":
                        switch(selectBelow){
                            //代表省份
                            case "1":
                                url=Constant.BASE_URL + Constant.url11 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            //代表全国
                            case "2":
                                url=Constant.BASE_URL + Constant.url12 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "3":
                                Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                                break;
                        }
                        break;
                    //2代表智力榜
                    case "智力榜":
                        switch(selectBelow){
                            case "1":
                                url=Constant.BASE_URL + Constant.url21 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            //代表全国
                            case "2":
                                url=Constant.BASE_URL + Constant.url22 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "3":
                                Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                                break;
                        }
                        break;
                    case "体力榜":
                        switch(selectBelow){
                            case "1":
                                url=Constant.BASE_URL + Constant.url31 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            //代表全国
                            case "2":
                                url=Constant.BASE_URL + Constant.url32 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "3":
                                Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                                break;
                        }
                        break;
                    case "魅力榜":
                        switch(selectBelow){
                            case "1":
                                url=Constant.BASE_URL + Constant.url41 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province="+province;
                                break;
                            //代表全国
                            case "2":
                                url=Constant.BASE_URL + Constant.url42 +
                                        "page=" + page +
                                        "&size=" + size+
                                        "&province= ";
                                break;
                            case "3":
                                Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                                break;
                        }
                        break;
                }
                if(selectBelow.equals("0")||selectBelow.equals("3")){
                    //如果selectBelow是0 说明还没选择地区 不做任何操作
                }else{
                    //如果selectBelow不是0 说明选择了地区 请求数据
                    getData();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //设置listview每个item的点击事件
        dataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //创建一个空的JSONObject 用于存放点击用户的详细数据
                JSONObject detailJsonObject=new JSONObject();
                try {
                    Gson gson=new Gson();
                    //拿到所有用户的详细数据的数组
                    JSONArray detailJsonArray=new JSONArray(gson.toJson(dataList));
                    //给空的JSONObject填充数据
                    detailJsonObject = detailJsonArray.getJSONObject(position);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //进行屏幕跳转操作
                Intent intent=new Intent();
                intent.putExtra("detailJson",detailJsonObject.toString());
                intent.setClass(getContext(), DataDetailActivity.class);
                startActivity(intent);
            }
        });
    }

    //处理下拉刷新和上拉加载更多事件的方法
    private void setListener(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if(selectBelow.equals("0")){//刷新之后 selectBelow是0 没有选择地区 toast显示
                    Toast.makeText(getContext(), "请选择地区", Toast.LENGTH_SHORT).show();
                    refreshLayout.finishRefresh();
                }else if(selectBelow.equals("3")){
                    Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                    refreshLayout.finishRefresh();
                }else{
                    //下拉刷新时回调，需要请求最新的数据
                    isRefresh = true;
                    url=url.replace("page="+page,"page=1");
                    page = 1;
                    //清空所有数据 重新请求
                    dataList.clear();
                    getData();
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(selectBelow.equals("0")){//刷新之后 selectBelow是0 没有选择地区 toast显示
                    Toast.makeText(getContext(), "请选择地区", Toast.LENGTH_SHORT).show();
                    refreshLayout.finishLoadMore();
                }else if(selectBelow.equals("3")){
                    Toast.makeText(getContext(), "您还没有设置省份", Toast.LENGTH_SHORT).show();
                    refreshLayout.finishLoadMore();
                }else{
                    //上拉加载更多时回调，需要请求更多的数据，分页查询
                    isRefresh = false;
                    url=url.replace("page="+page,"page="+(page+1));
                    page++;//页码加1
                    getData();
                }
            }
        });
    }

    //请求后端的数据
    private void getData(){
        Constant.logger.info("从服务端获取排行数据 开始");
        //向服务端传递当前请求的页码，每页显示的数据的条数
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Constant.logger.warn("从服务端获取排行数据: 失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String dataJson = response.body().string();
                    JSONObject jsonObject=new JSONObject(dataJson);
                    JSONObject dataObject=jsonObject.getJSONObject("data");
                    jsonArray=dataObject.getJSONArray("content");
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    //创建特殊类型的Gson 因为有Date类型
                    GsonBuilder builder = new GsonBuilder().setDateFormat("yyyy-MM-dd");
                    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                            return new Date(json.getAsJsonPrimitive().getAsLong());
                        }
                    });
                    Gson gson = builder.create();
                    Type type = new TypeToken<List<Data>>(){}.getType();
                    List<Data> datas=gson.fromJson(jsonArray.toString(),type);
                    //添加到数据源中
                    if (isRefresh){
                        dataList.addAll(0,datas);
                    }else {
                        dataList.addAll(datas);
                    }
                    //数据源发送改变，需要更新界面，使用Handler
                    Message message = new Message();
                    message.what = REFRESH;
                    myHandler.sendMessage(message);//发送到主线程的消息队列
                } catch (JSONException e) {
                    Constant.logger.warn("解析服务端Response: 失败", e);
                }
            }
        });
    }
}